package com.atguigu.common.valid;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.HashSet;

/**
 * @author centurion
 * @description: TODO
 * @date 2024/5/28
 */
public class ListValueConstraintValidator implements ConstraintValidator<ListValue, Integer> {

    private HashSet set = new HashSet<Integer>();

    /**
     * 初始化
     * @param constraintAnnotation
     */
    @Override
    public void initialize(ListValue constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
        int[] vals = constraintAnnotation.vals();
        if (vals.length>0) {
            Arrays.stream(vals).forEach(item->set.add(item));
        }
    }

    /**
     * 校验
     * @param value
     * @param context
     * @return
     */
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        return set.contains(value);
    }
}
